const { v4: uuidv4 } = require('uuid');
const getTime = require('../utils/getTime');
const { executeQuery } = require('../utils/dataAccess');

exports.getPost = async (req, res, next) => {
    let sqlStatement = `SELECT 
    post_id as postId,
    post_name as postName,
    post_sort as postSort,
    remark as remark
    FROM sys_post where 1=1`;

    if(req.body.postName){
        sqlStatement += ` and post_name like '%${req.body.postName}%'`;
    }

    sqlStatement += ` order by post_sort`;

    try{
        let result = await executeQuery(sqlStatement); 

        res.json({
            code: 200, 
            mssage: '查询成功', 
            data: result.rows
        });
    }
    catch (err) { next(err) }
}

exports.addPost = async (req, res, next) => {
    try {

        if(!req.body.postName || !req.body.postSort){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `INSERT INTO sys_post ( post_name, post_sort, remark, create_by, create_time, post_code, status) VALUES ('${req.body.postName}', '${req.body.postSort}', '${req.body.remark}', '${req.auth.user_name}', '${getTime()}', '${req.body.postCode}', '${req.body.status}')`;

        let result = await executeQuery(sqlStatement); 

        res.json({
            code: 200,
            mssage: '新增成功',
            data: result.rows
        })

    }
    catch (err) { next(err)}
}


exports.updatePost = async (req, res, next) => {
    try {
        if(!req.body.postId || !req.body.postName || !req.body.postSort){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `UPDATE sys_post SET post_name = '${req.body.postName}', post_sort = '${req.body.postSort}', remark = '${req.body.remark}', update_by = '${req.auth.user_name}', update_time = '${getTime()}' WHERE post_id = '${req.body.postId }'`;

        let result = await executeQuery(sqlStatement); 

        res.json({
            code: 200,
            mssage: '保存成功',
            data: result.rows
        })

    }
    catch (err) { next(err) }
}

exports.deletePost = async (req, res, next) => {
    try {
        if(!req.body.postId){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `DELETE FROM sys_post WHERE post_id = '${req.body.postId}'`;
        let sqlStatement2 = `DELETE FROM sys_user_post WHERE post_id = '${req.body.postId}'`;

        let result = await executeQuery(sqlStatement);
        let result2 = await executeQuery(sqlStatement2);

        res.json({
            code: 200, 
            msg: '删除成功',
            data: {
                result: result.rows,
                result2: result2.rows
            }
        });
    }
    catch (err) { next(err) }
}